package com.leyou.auth.config;

import com.leyou.common.utils.RsaUtils;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.boot.context.properties.ConfigurationProperties;

import java.security.PrivateKey;
import java.security.PublicKey;

/**
 * 将配置文件中所配置的属性映射到JwtProperties
 * TODO: 实现在Spring完成属性初始化后再加载密钥
 *
 * @author chao
 */
@Data
@Slf4j
@ConfigurationProperties(prefix = "ly.jwt")
public class JwtProperties implements InitializingBean {
    /**
     * 公钥路径
     */
    private String pubKeyPath;
    /**
     * 私钥路径
     */
    private String priKeyPath;

    private PublicKey publicKey;
    private PrivateKey privateKey;

    /**
     * 跟用户登录token相关的属性
     */
    private UserTokenProperties user = new UserTokenProperties();

    /**
     * 服务调用token信息
     */
    private AppTokenProperties app = new AppTokenProperties();

    @Data
    public class AppTokenProperties {
        private int expire;
        private Long id;
        private String name;
        private String headerName;
    }

    @Data
    public class UserTokenProperties {
        /**
         * 过期时间，单位分钟
         */
        private int expire;
        /**
         * 存放token的cookie名称
         */
        private String cookieName;
        /**
         * 存放token的cookie的domain
         */
        private String cookieDomain;
        /**
         * 刷新时间，单位分钟，如果小于这个时间，则重新生成token
         */
        private int refreshTime;

    }

    /**
     * 该方法允许bean实例在设置了所有bean属性之后执行总体配置的验证和最终的初始化。(初始化bean的时候执行当前方法)
     *
     * @throws Exception
     */
    @Override
    public void afterPropertiesSet() throws Exception {
        try {
            // 获取公钥和密钥
            this.publicKey = RsaUtils.getPublicKey(pubKeyPath);
            this.privateKey = RsaUtils.getPrivateKey(priKeyPath);
        } catch (Exception e) {
            log.error("初始化公钥和密钥失败：{}", e.getMessage());
            throw new RuntimeException(e);
        }

    }


}
